<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Proxy实例方法</title>
</head>
<body>
    <h1>Proxy实例的方法</h1>

    <script>
        // get()方法
        const person = {
            name: "张三"
        };
        const proxy = new Proxy(person, {
            get: function(target, propKey) {
                if (propKey in target) {
                    return target[propKey];
                } else {
                    throw new ReferenceError(`属性 "${propKey}" 不存在`);
                }
            }
        });
        console.log(proxy.name); // "张三"
        // console.log(proxy.age); // 抛出错误

        // set()方法
        const validator = {
            set: function(obj, prop, value) {
                if (prop === 'age') {
                    if (!Number.isInteger(value)) {
                        throw new TypeError('年龄必须是整数');
                    }
                    if (value > 200) {
                        throw new RangeError('年龄不合理');
                    }
                }
                obj[prop] = value;
                return true;
            }
        };
        const person2 = new Proxy({}, validator);
        person2.age = 100;
        // person2.age = 'young'; // 报错
        // person2.age = 300; // 报错

        // has()方法
        const handler = {
            has (target, key) {
                if (key[0] === '_') {
                    return false;
                }
                return key in target;
            }
        };
        const target = { _prop: 'foo', prop: 'foo' };
        const proxy2 = new Proxy(target, handler);
        console.log('_prop' in proxy2); // false
    </script>
</body>
</html> 